<?php

class Upload
{

    var $user_id = 0;
    var $folder_id = 0;
    var $catid;
    var $attachments;
    var $field;
    var $imageexts = array('gif', 'jpg', 'jpeg', 'png', 'bmp','rar','zip');
    var $uploadedfiles = array();
    var $downloadedfiles = array();
    var $error;
    var $upload_root;
    var $siteid;
    var $savepath;
    var $alowexts;
    var $site = array();
    public static $instances;

    /**
     *  实例化模板
     * @param type $name
     * @return type
     */
    public static function instance($dir)
    {
        if (!isset(Upload::$instances))
        {
            Upload::$instances = new Upload($dir);
        }
        return Upload::$instances;
    }

    function __construct($upload_dir = 'uploads')
    {
        $this->upload_dir = $upload_dir;
    }

    /**
     * 附件上传方法
     * @param $field 上传字段
     * @param $alowexts 允许上传类型
     * @param $maxsize 最大上传大小
     * @param $overwrite 是否覆盖原有文件
     * @param $thumb_setting 缩略图设置
     * @param $watermark_enable  是否添加水印
     */
    function uploads($field, $alow_exts = '', $temp_filename = '', $max_size = 10240000000, $over_write = 1)
    {

        /* 检查是否为上传的字段 */
        if (!isset($_FILES[$field]))
        {
            $this->error = UPLOAD_ERR_OK;
            return false;
            exit;
        }

        /* 检查上传类型 */
        if (empty($alow_exts) || $alow_exts == '')
        {
            $alow_exts = 'jpg';
        }

        $this->field = $field;
        $this->savepath = $this->upload_dir;
        $this->alowexts = $alow_exts;
        $this->maxsize = $max_size;
        $this->overwrite = $over_write;
        $uploadfiles = array();
        $description = '测试的';

        $this->uploads = 1;
        if (!$description)
            $description = '';
        $uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description' => $description, 'fn' => 'd');
        if (!is_dir($this->savepath))
        {
            File::create_path($this->savepath);
        }
        if (!is_writeable($this->savepath))
        {
            $this->error = '9';
            return false;
        }
        if (!$this->is_allow_upload())
        {
            $this->error = '13';
            return false;
        }
        
        foreach ($uploadfiles as $k => $file)
        {
            $fileext = $this->fileext($file['name']);
            if ($file['error'] != 0)
            {
                $this->error = $file['error'];
                return false;
            }

            if (!preg_match("/^(" . $this->alowexts . ")$/", $fileext))
            {
                $this->error = '10';
                return false;
            }
            if ($this->maxsize && $file['size'] > $this->maxsize)
            {
                $this->error = '11';
                return false;
            }
            
            if (!$this->isuploadedfile($file['tmp_name']))
            {
                $this->error = '12';
                return false;
            }

            if ($temp_filename == '')
            {
                $temp_filename = $this->getname($fileext);
            }
            else
            {
                $temp_filename = $temp_filename . '.' . $fileext;
            }

            $savefile = $this->savepath . $temp_filename;
            $savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile);
            $filepath = $savefile;
            $uploadedfile = array('file_name' => $file['name'], 'file_path' => $this->savepath, 'file_size' => $file['size'], 'file_ext' => $fileext, 'file_realname' => $temp_filename);
            if (!$this->overwrite && file_exists($savefile))
                continue;
            if (@move_uploaded_file($file['tmp_name'], $filepath))
            {
                $this->add($uploadedfile);
            }
        }
        return $this->uploadedfiles;
    }

    /**
     * 取得文件扩展
     * 
     * @param $filename 文件名
     * @return 扩展名
     */
    public function fileext($filename)
    {
        return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
    }

    /**
     * 附件删除方法
     * @param $where 删除sql语句
     */
    function delete($where)
    {
        $this->att_db = pc_base::load_model('attachment_model');
        $result = $this->att_db->select($where);
        foreach ($result as $r)
        {
            $image = $this->upload_root . $r['filepath'];
            @unlink($image);
            $thumbs = glob(dirname($image) . '/*' . basename($image));
            if ($thumbs)
                foreach ($thumbs as $thumb)
                    @unlink($thumb);
        }
        return $this->att_db->delete($where);
    }

    /**
     * 附件添加如数据库
     * @param $uploadedfile 附件信息
     */
    function add($uploadedfile)
    {
        if (count(Session::instance()->get('user')) > 0)
        {
            $uploadedfile['user_id'] = Session::instance()->get_detail('user', 'id');
        }
        $uploadedfile['ip'] = URL::get_ip();
        $uploadedfile['addtime'] = time();
        $uploadedfile['is_image'] = in_array($uploadedfile['file_ext'], $this->imageexts) ? 1 : 0;
        $this->uploadedfiles[] = $uploadedfile;
    }

    function set_userid($userid)
    {
        $this->userid = $userid;
    }

    /**
     * 获取缩略图地址..
     * @param $image 图片路径
     */
    function get_thumb($image)
    {
        return str_replace('.', '_thumb.', $image);
    }

    /**
     * 获取附件名称
     * @param $fileext 附件扩展名
     */
    function getname($fileext)
    {
        $str = '';
        for ($i = 0; $i < 9; $i++)
        {
            $str .= mt_rand(0, 9);
        }
        return date('Ymdhis') . $str . '.' . $fileext;
    }

    /**
     * 返回附件大小
     * @param $filesize 图片大小
     */
    function size($filesize)
    {
        if ($filesize >= 1073741824)
        {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
        }
        elseif ($filesize >= 1048576)
        {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
        }
        elseif ($filesize >= 1024)
        {
            $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
        }
        else
        {
            $filesize = $filesize . ' Bytes';
        }
        return $filesize;
    }

    /**
     * 判断文件是否是通过 HTTP POST 上传的
     *
     * @param	string	$file	文件地址
     * @return	bool	所给出的文件是通过 HTTP POST 上传的则返回 TRUE
     */
    function isuploadedfile($file)
    {
        return is_uploaded_file($file) || is_uploaded_file(str_replace('\\\\', '\\', $file));
    }

    /**
     * 补全网址
     *
     * @param	string	$surl		源地址
     * @param	string	$absurl		相对地址
     * @param	string	$basehref	网址
     * @return	string	网址
     */
    function fillurl($surl, $absurl, $basehref = '')
    {
        if ($basehref != '')
        {
            $preurl = strtolower(substr($surl, 0, 6));
            if ($preurl == 'http://' || $preurl == 'ftp://' || $preurl == 'mms://' || $preurl == 'rtsp://' || $preurl == 'thunde' || $preurl == 'emule://' || $preurl == 'ed2k://')
                return $surl;
            else
                return $basehref . '/' . $surl;
        }
        $i = 0;
        $dstr = '';
        $pstr = '';
        $okurl = '';
        $pathStep = 0;
        $surl = trim($surl);
        if ($surl == '')
            return '';
        $urls = @parse_url(SITE_URL);
        $HomeUrl = $urls['host'];
        $BaseUrlPath = $HomeUrl . $urls['path'];
        $BaseUrlPath = preg_replace("/\/([^\/]*)\.(.*)$/", '/', $BaseUrlPath);
        $BaseUrlPath = preg_replace("/\/$/", '', $BaseUrlPath);
        $pos = strpos($surl, '#');
        if ($pos > 0)
            $surl = substr($surl, 0, $pos);
        if ($surl[0] == '/')
        {
            $okurl = 'http://' . $HomeUrl . '/' . $surl;
        }
        elseif ($surl[0] == '.')
        {
            if (strlen($surl) <= 2)
                return '';
            elseif ($surl[0] == '/')
            {
                $okurl = 'http://' . $BaseUrlPath . '/' . substr($surl, 2, strlen($surl) - 2);
            }
            else
            {
                $urls = explode('/', $surl);
                foreach ($urls as $u)
                {
                    if ($u == "..")
                        $pathStep++;
                    else if ($i < count($urls) - 1)
                        $dstr .= $urls[$i] . '/';
                    else
                        $dstr .= $urls[$i];
                    $i++;
                }
                $urls = explode('/', $BaseUrlPath);
                if (count($urls) <= $pathStep)
                    return '';
                else
                {
                    $pstr = 'http://';
                    for ($i = 0; $i < count($urls) - $pathStep; $i++)
                    {
                        $pstr .= $urls[$i] . '/';
                    }
                    $okurl = $pstr . $dstr;
                }
            }
        }
        else
        {
            $preurl = strtolower(substr($surl, 0, 6));
            if (strlen($surl) < 7)
                $okurl = 'http://' . $BaseUrlPath . '/' . $surl;
            elseif ($preurl == "http:/" || $preurl == 'ftp://' || $preurl == 'mms://' || $preurl == "rtsp://" || $preurl == 'thunde' || $preurl == 'emule:' || $preurl == 'ed2k:/')
                $okurl = $surl;
            else
                $okurl = 'http://' . $BaseUrlPath . '/' . $surl;
        }
        $preurl = strtolower(substr($okurl, 0, 6));
        if ($preurl == 'ftp://' || $preurl == 'mms://' || $preurl == 'rtsp://' || $preurl == 'thunde' || $preurl == 'emule:' || $preurl == 'ed2k:/')
        {
            return $okurl;
        }
        else
        {
            $okurl = preg_replace('/^(http:\/\/)/i', '', $okurl);
            $okurl = preg_replace('/\/{1,}/i', '/', $okurl);
            return 'http://' . $okurl;
        }
    }

    /**
     * 是否允许上传
     */
    function is_allow_upload()
    {
        return true;
    }

    /**
     * 返回错误信息
     */
    function error()
    {
        $UPLOAD_ERROR = array(
            0 => L('att_upload_succ'),
            1 => L('att_upload_limit_ini'),
            2 => L('att_upload_limit_filesize'),
            3 => L('att_upload_limit_part'),
            4 => L('att_upload_nofile'),
            5 => '',
            6 => L('att_upload_notemp'),
            7 => L('att_upload_temp_w_f'),
            8 => L('att_upload_create_dir_f'),
            9 => L('att_upload_dir_permissions'),
            10 => L('att_upload_limit_ext'),
            11 => L('att_upload_limit_setsize'),
            12 => L('att_upload_not_allow'),
            13 => L('att_upload_limit_time'),
        );

        return iconv(CHARSET, "utf-8", $UPLOAD_ERROR[$this->error]);
    }

    /**
     * ck编辑器返回
     * @param $fn 
     * @param $fileurl 路径
     * @param $message 显示信息
     */
    function mkhtml($fn, $fileurl, $message)
    {
        $str = '<script type="text/javascript">window.parent.CKEDITOR.tools.callFunction(' . $fn . ', \'' . $fileurl . '\', \'' . $message . '\');</script>';
        exit($str);
    }

    /**
     * flash上传调试方法
     * @param $id
     */
    function uploaderror($id = 0)
    {
        file_put_contents(PHPCMS_PATH . 'xxx.txt', $id);
    }

    /**
     * 获取站点配置信息
     * @param  $siteid 站点id
     */
    private function _get_site_setting($siteid)
    {
        $siteinfo = getcache('sitelist', 'commons');
        return string2array($siteinfo[$siteid]['setting']);
    }

}

?>